
// 文件名称：notification.js
// 完整保存路径：miniprogram/pages/notification/notification.js
// 功能说明：通知页面逻辑控制
// 使用说明：处理通知列表展示、标记已读、设置管理等功能

const { getToken } = require('../../utils/auth.js');

const app = getApp();

Page({
  data: {
    activeTab: 0,
    tabs: [
      { id: 0, name: '全部', status: 'all' },
      { id: 1, name: '未读', status: 'unread' },
      { id: 2, name: '已读', status: 'read' }
    ],
    notifications: [],
    loading: false,
    hasMore: true,
    page: 1,
    perPage: 20,
    refreshing: false,
    unreadCount: 0
  },

  onLoad() {
    console.log('通知页面加载');
    this.loadNotifications();
    this.loadUnreadCount();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreNotifications();
    }
  },

  /**
   * 切换标签页
   */
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id;
    if (tabId === this.data.activeTab) return;
    
    this.setData({
      activeTab: tabId,
      notifications: [],
      page: 1,
      hasMore: true
    });
    
    this.loadNotifications();
  },

  /**
   * 加载通知列表
   */
  async loadNotifications() {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const currentTab = this.data.tabs[this.data.activeTab];
      const params = {
        page: this.data.page,
        per_page: this.data.perPage
      };
      
      if (currentTab.status !== 'all') {
        params.status = currentTab.status;
      }
      
      const response = await wx.request({
        url: `${app.globalData.apiBaseUrl}/notifications`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: params
      });
      
      if (response.statusCode === 200 && response.data.success) {
        const result = response.data.data;
        
        this.setData({
          notifications: this.data.page === 1 ? result.notifications : [...this.data.notifications, ...result.notifications],
          hasMore: result.pagination.has_next,
          loading: false,
          refreshing: false
        });
        
        wx.stopPullDownRefresh();
      } else {
        throw new Error(response.data.message || '获取通知失败');
      }
      
    } catch (error) {
      console.error('加载通知失败:', error);
      this.setData({
        loading: false,
        refreshing: false
      });
      
      wx.stopPullDownRefresh();
      wx.showToast({
        title: error.message || '加载通知失败',
        icon: 'error'
      });
    }
  },

  /**
   * 加载更多通知
   */
  loadMoreNotifications() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadNotifications();
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    });
    
    await Promise.all([
      this.loadNotifications(),
      this.loadUnreadCount()
    ]);
  },

  /**
   * 加载未读通知数量
   */
  async loadUnreadCount() {
    try {
      const token = getToken();
      if (!token) return;
      
      const response = await wx.request({
        url: `${app.globalData.apiBaseUrl}/notifications/unread-count`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.statusCode === 200 && response.data.success) {
        this.setData({
          unreadCount: response.data.data.unread_count
        });
      }
      
    } catch (error) {
      console.error('获取未读数量失败:', error);
    }
  },

  /**
   * 标记通知为已读
   */
  async onMarkAsRead(e) {
    const notificationId = e.currentTarget.dataset.id;
    
    try {
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await wx.request({
        url: `${app.globalData.apiBaseUrl}/notifications/${notificationId}/read`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.statusCode === 200 && response.data.success) {
        // 更新本地数据
        const notifications = this.data.notifications.map(item => {
          if (item.id === notificationId) {
            return { ...item, status: 'read', read_at: new Date().toISOString() };
          }
          return item;
        });
        
        this.setData({ notifications });
        
        // 重新加载未读数量
        this.loadUnreadCount();
        
        wx.showToast({
          title: '已标记为已读',
          icon: 'success'
        });
      } else {
        throw new Error(response.data.message || '标记已读失败');
      }
      
    } catch (error) {
      console.error('标记已读失败:', error);
      wx.showToast({
        title: error.message || '标记已读失败',
        icon: 'error'
      });
    }
  },

  /**
   * 标记所有通知为已读
   */
  async onMarkAllAsRead() {
    try {
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await wx.request({
        url: `${app.globalData.apiBaseUrl}/notifications/read-all`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.statusCode === 200 && response.data.success) {
        // 更新本地数据
        const notifications = this.data.notifications.map(item => ({
          ...item,
          status: 'read',
          read_at: new Date().toISOString()
        }));
        
        this.setData({ 
          notifications,
          unreadCount: 0
        });
        
        wx.showToast({
          title: response.data.message,
          icon: 'success'
        });
      } else {
        throw new Error(response.data.message || '批量标记失败');
      }
      
    } catch (error) {
      console.error('批量标记已读失败:', error);
      wx.showToast({
        title: error.message || '批量标记失败',
        icon: 'error'
      });
    }
  },

  /**
   * 跳转到通知设置页面
   */
  onSettings() {
    wx.navigateTo({
      url: '/pages/notification/settings/settings'
    });
  },

  /**
   * 发送测试通知
   */
  async onSendTest() {
    try {
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await wx.request({
        url: `${app.globalData.apiBaseUrl}/notifications/test`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          notification_type: 'system',
          title: '测试通知',
          content: '这是一条测试通知，用于验证通知功能是否正常。'
        }
      });
      
      if (response.statusCode === 200 && response.data.success) {
        wx.showToast({
          title: '测试通知已发送',
          icon: 'success'
        });
        
        // 刷新通知列表
        this.refreshData();
      } else {
        throw new Error(response.data.message || '发送测试通知失败');
      }
      
    } catch (error) {
      console.error('发送测试通知失败:', error);
      wx.showToast({
        title: error.message || '发送测试通知失败',
        icon: 'error'
      });
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`;
    }
    
    // 小于24小时
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`;
    }
    
    // 小于30天
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`;
    }
    
    // 超过30天显示具体日期
    return date.toLocaleDateString();
  },

  /**
   * 格式化通知类型
   */
  formatNotificationType(type) {
    const typeMap = {
      'system': '系统通知',
      'intervention': '干预提醒',
      'vision': '视力检查',
      'share': '社交分享'
    };
    return typeMap[type] || type;
  },

  /**
   * 格式化优先级
   */
  formatPriority(priority) {
    const priorityMap = {
      'low': '低',
      'normal': '普通',
      'high': '高',
      'urgent': '紧急'
    };
    return priorityMap[priority] || priority;
  }
}); 